<template>
  <div class="device-usage-statistics">
    <a-card :bordered="false" class="statistics-card">
      <template #title>
        <div class="card-title">
          <icon-bar-chart style="font-size: 20px; margin-right: 8px;" />
          <span>物资使用情况统计</span>
        </div>
      </template>

      <!-- 查询条件 -->
      <div class="query-section">
        <a-space wrap>
          <a-range-picker
            v-model="dateRange"
            :default-value="defaultDateRange"
            format="YYYY-MM-DD"
            style="width: 300px"
            @change="handleDateChange"
          />
          <a-button type="primary" @click="handleSearch">
            <template #icon><icon-search /></template>
            查询
          </a-button>
          <a-button @click="handleReset">
            <template #icon><icon-refresh /></template>
            重置
          </a-button>
        </a-space>
      </div>

      <!-- Tab切换 -->
      <a-tabs v-model:active-key="activeTab" @change="handleTabChange">
        <!-- 传感器统计 -->
        <a-tab-pane key="sensor" title="传感器统计">
          <div class="sensor-statistics">
            <!-- 传感器筛选条件 -->
            <div class="filter-section">
              <a-space wrap>
                <a-input
                  v-model="sensorQuery.modelId"
                  placeholder="请输入型号"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="sensorQuery.manufacturer"
                  placeholder="请输入生产厂家"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="sensorQuery.source"
                  placeholder="请输入购置来源"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-radio-group v-model="sensorGroupMode" type="button">
                  <a-radio value="deviceName">按设备名称</a-radio>
                  <a-radio value="modelId">按型号</a-radio>
                  <a-radio value="source">按购置来源</a-radio>
                </a-radio-group>
                <a-button type="primary" @click="loadSensorStatistics">
                  <template #icon><icon-search /></template>
                  查询
                </a-button>
              </a-space>
            </div>

            <div class="chart-wrapper">
              <div ref="sensorChartRef" class="chart-container" />
            </div>

            <!-- 传感器统计表格 -->
            <a-table
              :columns="sensorColumns"
              :data="sensorData"
              :loading="sensorLoading"
              :pagination="false"
              :bordered="true"
              :scroll="{ x: 1200 }"
            >
              <template #totalCount="{ record }">
                <a-statistic :value="record.totalCount" :value-style="{ fontSize: '16px' }" />
              </template>
              <template #stockCount="{ record }">
                <a-statistic :value="record.stockCount" :value-style="{ fontSize: '16px', color: '#52c41a' }" />
              </template>
              <template #usedCount="{ record }">
                <a-statistic :value="record.usedCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 耗材统计 -->
        <a-tab-pane key="consumable" title="耗材统计">
          <div class="consumable-statistics">
            <!-- 耗材筛选条件 -->
            <div class="filter-section">
              <a-space wrap>
                <a-input
                  v-model="consumableQuery.deviceName"
                  placeholder="请输入设备名称"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="consumableQuery.modelId"
                  placeholder="请输入型号"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="consumableQuery.manufacturer"
                  placeholder="请输入生产厂家"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-button type="primary" @click="loadConsumableStatistics">
                  <template #icon><icon-search /></template>
                  查询
                </a-button>
              </a-space>
            </div>

            <div class="chart-wrapper dual">
              <div ref="consumableStockChartRef" class="chart-container" />
              <div ref="consumableProjectChartRef" class="chart-container" />
            </div>

            <!-- 耗材统计表格 -->
            <a-table
              :columns="consumableColumns"
              :data="consumableData"
              :loading="consumableLoading"
              :pagination="false"
              :bordered="true"
              :scroll="{ x: 1200 }"
            >
              <template #remainingStock="{ record }">
                <a-statistic :value="record.remainingStock" :value-style="{ fontSize: '16px', color: '#52c41a' }" />
              </template>
              <template #usedCount="{ record }">
                <a-statistic :value="record.usedCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
              </template>
              <template #projectUsage="{ record }">
                <a-button type="text" size="small" @click="showProjectUsage(record)">
                  查看详情
                </a-button>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 项目使用明细弹窗 -->
    <a-modal
      v-model:visible="projectUsageVisible"
      title="各项目使用数量明细"
      :width="800"
      :footer="false"
    >
      <div class="chart-wrapper">
        <div ref="projectUsageChartRef" class="chart-container small" />
      </div>
      <a-table
        :columns="projectUsageColumns"
        :data="projectUsageData"
        :pagination="false"
        :bordered="true"
      >
        <template #usageCount="{ record }">
          <a-statistic :value="record.usageCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs, { type Dayjs } from 'dayjs'
import * as echarts from 'echarts'
import {
  getSensorStatistics,
  getConsumableStatistics,
  type SensorStatisticsQuery,
  type ConsumableStatisticsQuery,
  type SensorStatisticsResp,
  type ConsumableStatisticsResp,
  type ProjectUsageDetail
} from '@/apis/generator/deviceStore'

const currentYear = dayjs().year()
const defaultDateRange = [dayjs(`${currentYear}-01-01`), dayjs(`${currentYear}-12-31`)]

const dateRange = ref<[Dayjs, Dayjs]>(defaultDateRange as [Dayjs, Dayjs])
const activeTab = ref('sensor')

const sensorQuery = ref<SensorStatisticsQuery>({
  modelId: '',
  manufacturer: '',
  source: ''
})

const consumableQuery = ref<ConsumableStatisticsQuery>({
  deviceName: '',
  modelId: '',
  manufacturer: ''
})

const sensorData = ref<SensorStatisticsResp[]>([])
const sensorLoading = ref(false)

const consumableData = ref<ConsumableStatisticsResp[]>([])
const consumableLoading = ref(false)

const projectUsageVisible = ref(false)
const projectUsageData = ref<ProjectUsageDetail[]>([])

const sensorGroupMode = ref<'deviceName' | 'modelId' | 'source'>('deviceName')

const sensorChartRef = ref<HTMLElement>()
const consumableStockChartRef = ref<HTMLElement>()
const consumableProjectChartRef = ref<HTMLElement>()
const projectUsageChartRef = ref<HTMLElement>()

let sensorChart: echarts.ECharts | null = null
let consumableStockChart: echarts.ECharts | null = null
let consumableProjectChart: echarts.ECharts | null = null
let projectUsageChart: echarts.ECharts | null = null

const sensorColumns = [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    width: 120
  },
  {
    title: '生产厂家',
    dataIndex: 'manufacturer',
    width: 150
  },
  {
    title: '购置来源',
    dataIndex: 'source',
    width: 150
  },

  {
    title: '总数量',
    dataIndex: 'totalCount',
    width: 120,
    slotName: 'totalCount'
  },
  {
    title: '库存数量',
    dataIndex: 'stockCount',
    width: 120,
    slotName: 'stockCount'
  },
  {
    title: '使用数量',
    dataIndex: 'usedCount',
    width: 120,
    slotName: 'usedCount'
  }
]

const consumableColumns = [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    width: 120
  },
  {
    title: '生产厂家',
    dataIndex: 'manufacturer',
    width: 150
  },
  {
    title: '剩余库存数量',
    dataIndex: 'remainingStock',
    width: 140,
    slotName: 'remainingStock'
  },
  {
    title: '使用数量',
    dataIndex: 'usedCount',
    width: 120,
    slotName: 'usedCount'
  },
  {
    title: '各项目使用数量',
    dataIndex: 'projectUsage',
    width: 150,
    slotName: 'projectUsage'
  }
]

const projectUsageColumns = [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 200
  },
  {
    title: '使用数量',
    dataIndex: 'usageCount',
    width: 150,
    slotName: 'usageCount'
  }
]

const sensorGroupLabelMap = {
  deviceName: '设备名称',
  modelId: '型号',
  source: '购置来源'
} as const

const groupedSensorStats = computed(() => {
  const map = new Map<string, { name: string; stock: number; used: number; total: number }>()
  const mode = sensorGroupMode.value

  sensorData.value.forEach(item => {
    const label = mode === 'deviceName'
      ? item.deviceName
      : mode === 'modelId'
        ? item.modelId
        : item.source || ''

    const key = (label || '').trim() || '未填写'
    const record = map.get(key) ?? { name: key, stock: 0, used: 0, total: 0 }
    record.stock += Number(item.stockCount ?? 0)
    record.used += Number(item.usedCount ?? 0)
    record.total += Number(item.totalCount ?? 0)
    map.set(key, record)
  })

  return Array.from(map.values()).sort((a, b) => b.total - a.total)
})

const consumableProjectUsageSummary = computed(() => {
  const map = new Map<string, number>()

  consumableData.value.forEach(item => {
    item.projectUsageDetails?.forEach(detail => {
      const projectName = (detail.projectName || '').trim() || `项目${detail.projectId ?? ''}` || '未填写'
      const current = map.get(projectName) ?? 0
      map.set(projectName, current + Number(detail.usageCount ?? 0))
    })
  })

  return Array.from(map.entries())
    .map(([name, value]) => ({ name, value }))
    .sort((a, b) => b.value - a.value)
})

const disposeSensorChart = () => {
  if (sensorChart) {
    sensorChart.dispose()
    sensorChart = null
  }
}

const disposeConsumableCharts = () => {
  if (consumableStockChart) {
    consumableStockChart.dispose()
    consumableStockChart = null
  }
  if (consumableProjectChart) {
    consumableProjectChart.dispose()
    consumableProjectChart = null
  }
}

const disposeProjectUsageChart = () => {
  if (projectUsageChart) {
    projectUsageChart.dispose()
    projectUsageChart = null
  }
}

const handleWindowResize = () => {
  sensorChart?.resize()
  consumableStockChart?.resize()
  consumableProjectChart?.resize()
  projectUsageChart?.resize()
}

const renderSensorChart = () => {
  if (!sensorChartRef.value) return

  disposeSensorChart()
  sensorChart = echarts.init(sensorChartRef.value)

  const chartTitle = `传感器数量统计（按${sensorGroupLabelMap[sensorGroupMode.value]}）`
  const stats = groupedSensorStats.value

  if (!stats.length) {
    sensorChart.setOption({
      title: {
        text: chartTitle,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    })
    return
  }

  const categories = stats.map(item => item.name)
  const usedSeries = stats.map(item => Number(item.used ?? 0))
  const stockSeries = stats.map(item => Number(item.stock ?? 0))

  sensorChart.setOption({
    title: {
      text: chartTitle,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any[]) => {
        if (!params?.length) return ''
        const total = params.reduce((sum, current) => sum + (Number(current.value) || 0), 0)
        const lines = params
          .map(item => `${item.marker}${item.seriesName}：${item.value}`)
          .join('<br/>')
        return `${params[0].axisValueLabel || params[0].axisValue}<br/>${lines}<br/>合计：${total}`
      }
    },
    legend: {
      top: 30,
      data: ['使用数量', '库存数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: categories.length > 8 ? 80 : 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: categories.length > 8 ? 30 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '使用数量',
        type: 'bar',
        stack: '总量',
        data: usedSeries,
        itemStyle: { color: '#1890ff' }
      },
      {
        name: '库存数量',
        type: 'bar',
        stack: '总量',
        data: stockSeries,
        itemStyle: { color: '#52c41a' }
      }
    ]
  })
}

const renderConsumableStockChart = () => {
  if (!consumableStockChartRef.value) return

  if (consumableStockChart) {
    consumableStockChart.dispose()
  }
  consumableStockChart = echarts.init(consumableStockChartRef.value)

  const title = '耗材库存及使用情况'
  const data = consumableData.value

  if (!data.length) {
    consumableStockChart.setOption({
      title: {
        text: title,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    })
    return
  }

  const categories = data.map(item => {
    const name = item.deviceName || '未命名耗材'
    const model = item.modelId ? `（${item.modelId}）` : ''
    return `${name}${model}`
  })
  const remainingSeries = data.map(item => Number(item.remainingStock ?? 0))
  const usedSeries = data.map(item => Number(item.usedCount ?? 0))

  consumableStockChart.setOption({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any[]) => {
        if (!params?.length) return ''
        const lines = params
          .map(item => `${item.marker}${item.seriesName}：${item.value}`)
          .join('<br/>')
        return `${params[0].axisValue}<br/>${lines}`
      }
    },
    legend: {
      top: 30,
      data: ['使用数量', '剩余库存']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: categories.length > 6 ? 80 : 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: categories.length > 6 ? 30 : 0
      }
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '使用数量',
        type: 'bar',
        stack: '总量',
        data: usedSeries,
        itemStyle: { color: '#1890ff' }
      },
      {
        name: '剩余库存',
        type: 'bar',
        stack: '总量',
        data: remainingSeries,
        itemStyle: { color: '#73d13d' }
      }
    ]
  })
}

const renderConsumableProjectChart = () => {
  if (!consumableProjectChartRef.value) return

  if (consumableProjectChart) {
    consumableProjectChart.dispose()
  }
  consumableProjectChart = echarts.init(consumableProjectChartRef.value)

  const title = '耗材各项目使用占比'
  const data = consumableProjectUsageSummary.value

  if (!data.length) {
    consumableProjectChart.setOption({
      title: {
        text: title,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无项目使用数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    })
    return
  }

  const topData = data.slice(0, 10)

  consumableProjectChart.setOption({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => `${params.name}<br/>使用数量：${params.value}`
    },
    legend: {
      top: 30,
      type: 'scroll'
    },
    series: [
      {
        name: '使用数量',
        type: 'pie',
        radius: ['35%', '70%'],
        center: ['50%', '60%'],
        data: topData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
          }
        }
      }
    ]
  })
}

const renderProjectUsageChart = () => {
  if (!projectUsageVisible.value || !projectUsageChartRef.value) return

  if (projectUsageChart) {
    projectUsageChart.dispose()
  }
  projectUsageChart = echarts.init(projectUsageChartRef.value)

  const title = '各项目使用数量'
  const data = projectUsageData.value

  if (!data.length) {
    projectUsageChart.setOption({
      title: {
        text: title,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fontSize: 16,
          fill: '#999'
        }
      }
    })
    return
  }

  const categories = data.map(item => (item.projectName || '').trim() || `项目${item.projectId ?? ''}`)
  const usageSeries = data.map(item => Number(item.usageCount ?? 0))

  projectUsageChart.setOption({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: categories.length > 6 ? 60 : 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0,
        rotate: categories.length > 6 ? 30 : 0
      }
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '使用数量',
        type: 'bar',
        data: usageSeries,
        itemStyle: { color: '#1890ff' }
      }
    ]
  })
}

watch([sensorData, sensorGroupMode], async () => {
  if (activeTab.value !== 'sensor') return
  await nextTick()
  renderSensorChart()
}, { deep: true })

watch(consumableData, async () => {
  if (activeTab.value !== 'consumable') return
  await nextTick()
  renderConsumableStockChart()
  renderConsumableProjectChart()
}, { deep: true })

watch(activeTab, async (tab) => {
  await nextTick()
  if (tab === 'sensor') {
    renderSensorChart()
  } else if (tab === 'consumable') {
    renderConsumableStockChart()
    renderConsumableProjectChart()
  }
})

watch(projectUsageVisible, async visible => {
  if (visible) {
    await nextTick()
    renderProjectUsageChart()
  } else {
    disposeProjectUsageChart()
  }
})

watch(projectUsageData, async () => {
  if (projectUsageVisible.value) {
    await nextTick()
    renderProjectUsageChart()
  }
}, { deep: true })

const handleDateChange = (dates: [Dayjs, Dayjs] | null) => {
  if (dates) {
    dateRange.value = dates
  }
}

const handleTabChange = (key: string) => {
  if (key === 'sensor') {
    loadSensorStatistics()
  } else if (key === 'consumable') {
    loadConsumableStatistics()
  }
}

const handleSearch = () => {
  if (activeTab.value === 'sensor') {
    loadSensorStatistics()
  } else {
    loadConsumableStatistics()
  }
}

const handleReset = () => {
  dateRange.value = defaultDateRange as [Dayjs, Dayjs]
  sensorQuery.value = {
    modelId: '',
    manufacturer: '',
    source: ''
  }
  consumableQuery.value = {
    deviceName: '',
    modelId: '',
    manufacturer: ''
  }
  sensorGroupMode.value = 'deviceName'
  handleSearch()
}

const loadSensorStatistics = async () => {
  try {
    sensorLoading.value = true
    const query: SensorStatisticsQuery = {
      startDate: dateRange.value[0].format('YYYY-MM-DD'),
      endDate: dateRange.value[1].format('YYYY-MM-DD'),
      ...sensorQuery.value
    }
    
    const res = await getSensorStatistics(query)
    const result = res.data
    if (res.success && result?.success && Array.isArray(result.data)) {
      sensorData.value = result.data
    } else {
      Message.error(result?.message || result?.msg || '查询传感器统计失败')
      sensorData.value = []
    }
  } catch (error: any) {
    console.error('查询传感器统计失败:', error)
    Message.error(error?.message || '查询传感器统计失败')
    sensorData.value = []
  } finally {
    sensorLoading.value = false
  }
}

const loadConsumableStatistics = async () => {
  try {
    consumableLoading.value = true
    const query: ConsumableStatisticsQuery = {
      startDate: dateRange.value[0].format('YYYY-MM-DD'),
      endDate: dateRange.value[1].format('YYYY-MM-DD'),
      ...consumableQuery.value
    }
    
    const res = await getConsumableStatistics(query)
    const result = res.data
    if (res.success && result?.success && Array.isArray(result.data)) {
      consumableData.value = result.data
    } else {
      Message.error(result?.message || result?.msg || '查询耗材统计失败')
      consumableData.value = []
    }
  } catch (error: any) {
    console.error('查询耗材统计失败:', error)
    Message.error(error?.message || '查询耗材统计失败')
    consumableData.value = []
  } finally {
    consumableLoading.value = false
  }
}

const showProjectUsage = (record: ConsumableStatisticsResp) => {
  if (record.projectUsageDetails && record.projectUsageDetails.length > 0) {
    projectUsageData.value = record.projectUsageDetails
    projectUsageVisible.value = true
  } else {
    Message.info('暂无项目使用明细')
  }
}

onMounted(() => {
  window.addEventListener('resize', handleWindowResize)
  loadSensorStatistics()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleWindowResize)
  disposeSensorChart()
  disposeConsumableCharts()
  disposeProjectUsageChart()
})
</script>

<style scoped lang="scss">
.device-usage-statistics {
  padding: 20px;

  .statistics-card {
    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .query-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #fafafa;
    border-radius: 4px;
  }

  .filter-section {
    margin-bottom: 16px;
    padding: 12px;
    background: #fafafa;
    border-radius: 4px;
  }

  .sensor-statistics,
  .consumable-statistics {
    margin-top: 16px;
  }

  .chart-wrapper {
    margin-bottom: 16px;

    .chart-container {
      width: 100%;
      height: 320px;
      border: 1px solid #f0f0f0;
      border-radius: 4px;
    }

    .chart-container.small {
      height: 260px;
    }
  }

  .chart-wrapper.dual {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 16px;

    .chart-container {
      height: 320px;
    }
  }
}
</style>

